<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="序号" prop="planId">
        <el-input
            v-model="queryParams.planId"
            placeholder="请输入计划id"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="packNo">
        <el-input
            v-model="queryParams.packNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入品名"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材料" prop="typeDesc">
        <el-input
            v-model="queryParams.typeDesc"
            placeholder="请输入材料"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="materialQulity">
        <el-input
            v-model="queryParams.materialQulity"
            placeholder="请输入规格"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产日期" prop="prdTime">
        <el-date-picker clearable
                        v-model="queryParams.prdTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
            v-model="queryParams.unit"
            placeholder="请输入单位"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入数量"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="mark">
        <el-input
            v-model="queryParams.mark"
            placeholder="请输入备注"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="运单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入运单号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="明细id" prop="detailId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.detailId"-->
      <!--          placeholder="请输入明细id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['pro:pack:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['pro:pack:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['pro:pack:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['pro:pack:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" >
        <template slot-scope="scope">
          <router-link :to="'/mes/pro/goods-detail/index/' + scope.row.id " class="link-type">
            <span style="display: inline-block; width:120px">{{ scope.row.id }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="计划id" align="center" prop="planId" />
      <el-table-column label="订单号" align="center" prop="packNo" />
      <el-table-column label="品名" align="center" prop="name" />
      <el-table-column label="材料" align="center" prop="typeDesc" />
      <el-table-column label="规格" align="center" prop="materialQulity" />
      <el-table-column label="生产日期" align="center" prop="prdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.prdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="备注" align="center" prop="mark" />
      <el-table-column label="运单号" align="center" prop="orderNo" />
      <!--      <el-table-column label="明细id" align="center" prop="detailId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['pro:pack:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pro:pack:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="printPackIcon(scope.row)"
              v-hasPermi="['pro:pack:remove']"
          >打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改pack对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划id" prop="planId">
          <el-input v-model="form.planId" placeholder="请输入计划id" :disabled="true"/>
        </el-form-item>
        <el-form-item label="订单号" prop="packNo">
          <el-input v-model="form.packNo" placeholder="请输入订单号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入品名" :disabled="true"/>
        </el-form-item>
        <el-form-item label="材料" prop="typeDesc">
          <el-input v-model="form.typeDesc" placeholder="请输入材料" :disabled="true"/>
        </el-form-item>
        <el-form-item label="规格" prop="materialQulity">
          <el-input v-model="form.materialQulity" placeholder="请输入规格" :disabled="true"/>
        </el-form-item>
        <el-form-item label="生产日期" prop="prdTime">
          <el-date-picker clearable
                          v-model="form.prdTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择生产日期" :disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" :disabled="true"/>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="mark">
          <el-input v-model="form.mark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="运单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入运单号" />
        </el-form-item>
        <!--        <el-form-item label="明细id" prop="detailId">-->
        <!--          <el-input v-model="form.detailId" placeholder="请输入明细id" :disabled="true"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPack, getPack, delPack, addPack, updatePack } from "@/api/mes/pro/pack";
import {printPackList} from "@/api/mes/pro/goodsPlan";
import {getInfoByQrcodes, getInfoListByQrcodes} from "@/api/mes/wm/records";
import {listSelectErpCode} from "@/api/mes/csm/archive";

export default {
  name: "Pack",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // pack表格数据
      packList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,        packNo: null,        name: null,        typeDesc: null,        materialQulity: null,        prdTime: null,        unit: null,        amount: null,        mark: null,        orderNo: null,        detailId: null      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.queryParams.planId = this.$route.params.id
    this.getList();
    this.loadProductCode();
    this.connectWebSocket();
  },
  methods: {
    loadProductCode() {
      listSelectErpCode().then(response => {
        console.log(response)
        // this.productCode = response.data;
        this.productCode = response.data['pcode'];
      });
    },
    connectWebSocket: function() {
      // 创建 WebSocket 连接
      // const socket = new WebSocket('ws://127.0.0.1:1883')
      this.socket = new WebSocket('ws://127.0.0.1:1883')

      //最大尝试链接次数
      const maxReconnectAttempts = 20;
      let reconnectCount = 0;
      const reconnectInterval = 1000; // 1秒

      const tryReconnect = () => {
        if (reconnectCount < maxReconnectAttempts) {
          console.log('Reconnecting...');
          this.connectWebSocket();
          reconnectCount++;
        } else {
          console.log('Exceeded max reconnect attempts, stopping reconnecting.');
        }
      };

      this.socket.addEventListener('open', (event) => {
        console.log('WebSocket 连接已建立')
        let msg = {
          // clientName: '发送erp仓库连接消息',
          clientName: '',
          message: null,
          printPiece: 1,
          labelInfo: null
        }
        let json = JSON.stringify(msg)
        this.socket.send(json)
      })
      this.socket.addEventListener('message', (event) => {
        //接收到的数据
        const receivedData = event.data;
        // alert('接收到的信息receivedData：  ' + receivedData);

        //判断是否是二维码  根据.截取  3 4 5段为二维码
        // 使用 split 方法将字符串按点号拆分成数组
        const splitArray = receivedData.split('.');
        const arrayLength = splitArray.length;
        // alert("arrayLength：  "+ arrayLength);

        //判断执行是执行二维码操作还是执行分包合并操作  默认是二维码
        let codeHandle = false;
        // 判断 length 是否为 3、4 或 5
        if (arrayLength === 3 || arrayLength === 4 || arrayLength === 5) {
          codeHandle = true;
        }

        // //判断是否是二维码，如果是就赋到数组中 ； 如果不是就赋值操作类型 在根据操作类型弹出相应的弹窗
        if(codeHandle){
          this.addToQrcodeS(receivedData);
          // const qrcodeSArray = JSON.stringify(this.qrcodeS);
        }
        // this.form.qrcodeArray =  this.qrcodeS;
        // 返现页面
        if (this.qrcodeS && this.qrcodeS.length > 0) {
          getInfoByQrcodes(this.qrcodeS).then(response => {
            // this.form.qrcodeArray =  this.qrcodeS;
            console.log(this.formBox.sendNum+"======================");
            if(false){
              this.$message.error('扫码数量不能大于上限');
            }else {
              getInfoListByQrcodes(this.qrcodeS).then(response => {
                this.tableData =  response.data;
              });
              this.form.qrcodeArray =  response.data.qrcodeArray;
              this.formBox.sumNum = response.data.sumNum;
            }
          });


        }
        console.log('Received data:', receivedData)
      })

      // socket.addEventListener('close', (event) => {
      this.socket.addEventListener('close', (event) => {
        console.log('WebSocket connection closed')
        // 在连接关闭时触发重连逻辑
        // setTimeout(() => {
        //   console.log('Reconnecting...')
        //   this.connectWebSocket()
        // }, 1000) // 1秒后重连

        // 清除重连计数，防止无限递增
        reconnectCount = 0;
        // 在连接关闭后，间隔一段时间进行重连
        setTimeout(tryReconnect, reconnectInterval);
      })

      // socket.addEventListener('error', (event) => {
      this.socket.addEventListener('error', (event) => {
        console.error('WebSocket error:', event)
        // 在错误发生时触发重连逻辑
        // setTimeout(() => {
        //   console.log('Reconnecting...')
        //   this.connectWebSocket()
        // }, 1000) // 1秒后重连
        // 在连接错误后，间隔一段时间进行重连
        setTimeout(tryReconnect, reconnectInterval);
      })

      window.addEventListener('beforeunload', (event) => {
        // 当 tab 关闭时，关闭 WebSocket 连接
        this.socket.close();
      });

    },
    //添加二维码数组，过滤重复扫码
    addToQrcodeS(qrcode) {
      if (!this.qrcodeS.includes(qrcode)) {
        this.qrcodeS.push(qrcode);
      }
    },


    /** 查询pack列表 */
    getList() {
      this.loading = true;
      listPack(this.queryParams).then(response => {
        this.packList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        planId: null,        packNo: null,        name: null,        typeDesc: null,        materialQulity: null,        prdTime: null,        unit: null,        amount: null,        mark: null,        createTime: null,        updateTime: null,        orderNo: null,        detailId: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加pack";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPack(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改pack";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePack(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPack(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除pack编号为"' + ids + '"的数据项？').then(function() {
        return delPack(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    printPackIcon(data){
      const id = data.id
      printPackList(id).then(response => {
        this.$modal.msgSuccess("打印成功");
        this.msg = response.data;
        let json = JSON.stringify(this.msg);
        // socket.send(json);
        this.socket.send(json);
      });

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/pack/export', {
        ...this.queryParams
      }, `pack_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
